package com.itzhigui.service;

import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.itzhigui.bo.PaymentBo;
import com.itzhigui.config.AlipayConfig;
import com.itzhigui.entity.Cart;
import com.itzhigui.entity.PayInfo;
import com.itzhigui.entity.Product;
import com.itzhigui.mapper.CartMapper;
import com.itzhigui.mapper.PayInfoMapper;
import com.itzhigui.mapper.ProductMapper;
import com.itzhigui.utils.OrderUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 支付宝支付，业务实现
 *
 * @Author: 张兴宇
 * @DateTime: 2023/11/16 11:09
 **/
@Service
public class PayService {
    @Resource
    private AlipayConfig alipayConfig;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private CartMapper cartMapper;

    @Resource
    private ProductMapper productMapper;

    @Resource
    private PayInfoMapper payInfoMapper;
    /**
     * 下单支付
     *
     * @param bo
     * @return
     */
    public Object pay(PaymentBo bo) throws Exception {

        //获取订单号
        String orderNo = OrderUtil.getOrderNo();
        System.out.println("流水号" + orderNo);
        //将订单号和用户编号设置到redis
        // 984653186513====>21
        stringRedisTemplate.opsForValue().set(orderNo, bo.getUserId() + "");

        AlipayTradePagePayResponse response = Factory.Payment
                //选择网页支付平台
                .Page()
                //调用支付方法，设置订单名称
                .pay(bo.getSubject(), orderNo, bo.getTotal().toString(), alipayConfig.getReturnUrl());
        //生成支付界面
        return response.body;
    }

    /**
     * 修改支付状态
     *
     * @param map
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void updatePayStatus(Map<String, String[]> map) {
        //1.修改库存
        String orderNo = map.get("out_trade_no")[0];
        //获取用户编号
        Integer userId = Integer.valueOf(stringRedisTemplate.opsForValue().get(orderNo));
        //获取已购买的购物车信息
        List<Cart> cartBuyedList = cartMapper.findCartByUserIdAndBuyed(userId);
        cartBuyedList.forEach(cart -> {
            Integer productId = cart.getProductId();
            Integer quantity = cart.getQuantity();
            //根据商品id获取商品信息
            Product product = productMapper.findById(productId);
            //将商品库存减少
            product.setStock(product.getStock() - quantity);
            //更新会数据库
            productMapper.updateStock(product);
        });
        //2.删除当前用户已经购买的购物车信息
        cartMapper.deleteCartBuyedByUserId(userId);
        //3.添加支付信息
        PayInfo payInfo = new PayInfo();
        payInfo.setUserId(userId);//设置用户编号
        payInfo.setOrderNo(Long.parseLong(orderNo)); //设置订单号
        payInfo.setPayPlatform(1); //1.支付宝
        payInfo.setPlatformNumber(map.get("trade_no")[0]); //设置支付的流水号
        payInfo.setPlatformStatus(map.get("trade_status")[0]); //设置支付状态
        payInfo.setCreateTime(new Date());
        payInfo.setUpdateTime(new Date());
        payInfoMapper.add(payInfo);
        //4.删除redis中的订单号
        stringRedisTemplate.delete(orderNo);
    }
}
